const {verify} =require('../model/user')
const moment = require('moment');//moment格式化时间模块
const jwt = require('jwt-simple');//引入jwt模块
const appConfig=require('../config/config')
const { responsSuccess,responsError } = require("../utils/responseUtil");
const {validateParams}=require('../utils/validateReqParam')

module.exports.LoginController=function(request, response){
  console.log(request.body)
  validateParams(request.body, {
    'username': { type: 'string', default: '', required: true },
    'password': { type: 'string', default: '', required: true }
  }).then(reqData=>{
    const {expires,secret}=appConfig.chihiroUser
    const exp = moment().add(expires,'hours').valueOf();//算出七天后的时间，作为jwt.encode的第二个参数，表示过期时间
    const { username, password }=reqData
    verify(username,password).then(userData=>{
      const token = jwt.encode({
        iss: userData.id,
        exp
      }, secret);//第二个参数是jwt密钥
      responsSuccess(response,{token})
    }).catch(err=>{
      console.log('LoginController --> err',err)
      responsError(response,err)
    })
  }).catch(err=>{
    console.log('LoginController --> err',err)
    responsError(response,err)
  })
}

